package com.mmche.web.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easycoding.framework.annotation.Token;
import com.easycoding.framework.web.controller.BaseController;
import com.framework.base.util.Tool;
import com.mmche.common.Util;
import com.mmche.evaluate.pojo.EvaluateResult;
import com.mmche.evaluate.service.EvaluateResultService;

@Controller
public class EvaluateController extends BaseController{
	
	@Resource
	private EvaluateResultService evaluateResultService;
	
	
	@RequestMapping("/pinggu.html")
	@Token(create = true)
	private String evaluate(Map<String,Object> returnValue){
		returnValue.put("location", "evaluate");
		int year =Integer.parseInt(Tool.dateToString(new Date(),"yyyy"));
		List<Integer> yearList = new ArrayList<Integer>();
		for(int i=0;i<11;i++){
			yearList.add(year-10+i);
		}
		returnValue.put("years",yearList);
		return "evaluate/evaluate";
	}
	
	@RequestMapping("/pinggu/save.html")
	@Token(validate = true)
	private String save(){
		String brand = this.getRequestParameter("brand");//品牌
		String model = this.getRequestParameter("model");//车系
		String modelsId = this.getRequestParameter("modelsId");//车系编号
		String displacement = this.getRequestParameter("displacement");//排量
		String registerMonth = this.getRequestParameter("registerMonth");//月份
		String registerYear = this.getRequestParameter("registerYear");//年份
		String transmission = this.getRequestParameter("transmission");//变速想
		String mileage = this.getRequestParameter("mileage");//行驶里程
		EvaluateResult result = new EvaluateResult();
		result.setBrand(brand);
		result.setModel(model.replaceAll("　", ""));
		result.setModelId(modelsId);
		result.setDisplacement(displacement);
		result.setRegisterMonth(registerMonth);
		result.setRegisterYear(registerYear);
		result.setTransmission(transmission);
		result.setMileage(mileage);
		//麦麦车估价
		boolean at = false;
		if(transmission.equals("AT"))
			at = true;
		try{
			String evaluatePrice = Util.evaluate(modelsId, displacement, at, mileage, registerYear, registerMonth);
			JSONObject jsonObject = JSONObject.fromObject(evaluatePrice);
			String mmchePrice = jsonObject.getString("price");
			result.setMmchePrice(mmchePrice);
			JSONObject models = jsonObject.getJSONObject("models");
			if(!Tool.isEmpty(models)){//有版型价格
				Map<String,Double> modelPrices = new HashMap<String,Double>();
				for(Object key : models.keySet()){
					modelPrices.put(key.toString(),models.getDouble((key.toString())));
				}
				ArrayList<Entry<String,Double>> l = new ArrayList<Entry<String,Double>>(modelPrices.entrySet());    
		          
		        Collections.sort(l, new Comparator<Map.Entry<String, Double>>() {    
		            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {    
		                return o1.getValue().compareTo(o2.getValue());    
		            }    
		        });  
		        List<Map<String,String>> modelPrice = new ArrayList<Map<String,String>>();
//				        for(Entry<String,Double> e : l){
//				        	if(!Tool.isEmpty(e.getKey()) && e.getValue() != null && !Tool.isEmpty(e.getValue().toString())){
//					        	Map<String,String> p = new HashMap<String,String>();
//					        	p.put("model", e.getKey());
//					        	p.put("price", e.getValue().toString());
//					        	modelPrice.add(p);
//				        	}
//				        }
		        TreeMap<String,Double> tMap = new TreeMap<String,Double>(modelPrices);
				for(Entry<String,Double> e : tMap.entrySet()){
		        	if(!Tool.isEmpty(e.getKey()) && e.getValue() != null && !Tool.isEmpty(e.getValue().toString()) && Double.parseDouble(e.getValue().toString()) > 0.0){
			        	Map<String,String> p = new HashMap<String,String>();
			        	p.put("model", e.getKey());
			        	p.put("price", e.getValue().toString());
			        	modelPrice.add(p);
		        	}
		        }
		        //result.setMmchePrice(String.valueOf((((int)(l.get(0).getValue()*100+0.5))/100.00)));
		        if(Tool.isEmpty(mmchePrice) || Double.parseDouble(mmchePrice) == 0){
			        result.setMmchePrice(l.get(0).getValue().toString());
			        if(l.size()>1)
			        	//result.setMmchePrice(result.getMmchePrice() + "～" + String.valueOf((((int)(l.get(l.size()-1).getValue()*100+0.5))/100.00)));
			        	result.setMmchePrice(result.getMmchePrice() + "～" + l.get(l.size()-1).getValue().toString());
			        }
		        if((!Tool.isEmpty(mmchePrice) && Double.parseDouble(mmchePrice) != 0.0) || !Tool.isEmpty(models))
					result.setSuccess(true);
				result.setModelPrice(modelPrice);
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		this.evaluateResultService.saveEvaluateResult(result);
		return "redirect:/pinggu/" + result.getId() + ".html";
	}
	
	@RequestMapping("/pinggu/{id}.html")
	@Token(create = true)
	public String result(@PathVariable String id,Map<String,Object> returnValue){
		returnValue.put("result", this.evaluateResultService.findResultById(id));
		returnValue.put("location", "evaluate");
		int year =Integer.parseInt(Tool.dateToString(new Date(),"yyyy"));
		List<Integer> yearList = new ArrayList<Integer>();
		for(int i=0;i<11;i++){
			yearList.add(year-10+i);
		}
		returnValue.put("years",yearList);
		return "evaluate/result";
	}
}